#!/usr/bin/env python3
"""
简单的页面检查脚本
使用requests库检查页面内容
"""

import requests
import time
import re
from urllib.parse import urljoin

def check_page(url):
    """检查页面内容"""
    print(f"🌐 正在访问: {url}")
    
    try:
        # 发送请求
        response = requests.get(url, timeout=10)
        print(f"✅ HTTP状态码: {response.status_code}")
        
        if response.status_code != 200:
            print(f"❌ 页面返回错误状态码: {response.status_code}")
            return False
        
        # 获取页面内容
        content = response.text
        print(f"📊 页面内容长度: {len(content)} 字符")
        
        # 检查页面标题
        title_match = re.search(r'<title>(.*?)</title>', content, re.IGNORECASE)
        if title_match:
            title = title_match.group(1)
            print(f"📄 页面标题: {title}")
        
        # 检查是否有React应用内容
        react_indicators = [
            "软通动力自动驾驶小巴",
            "启动",
            "登录", 
            "硬件检测",
            "网络连接",
            "安全系统",
            "数据获取",
            "HMI 系统启动中"
        ]
        
        found_content = []
        for indicator in react_indicators:
            if indicator in content:
                found_content.append(indicator)
        
        if found_content:
            print(f"✅ 发现React应用内容: {', '.join(found_content)}")
        else:
            print("❌ 未发现React应用内容")
        
        # 检查是否有JavaScript错误
        if "error" in content.lower() or "Error" in content:
            print("⚠️  页面可能包含错误信息")
        
        # 检查根元素
        root_match = re.search(r'<div id="root">(.*?)</div>', content, re.DOTALL)
        if root_match:
            root_content = root_match.group(1).strip()
            if root_content:
                print(f"🎯 根元素有内容，长度: {len(root_content)} 字符")
                print(f"🎯 根元素内容预览: {root_content[:200]}...")
            else:
                print("❌ 根元素为空")
        else:
            print("❌ 未找到根元素")
        
        # 检查是否有React相关的脚本
        script_matches = re.findall(r'<script[^>]*src="([^"]*)"[^>]*>', content)
        react_scripts = [s for s in script_matches if 'main.tsx' in s or 'react' in s.lower()]
        if react_scripts:
            print(f"✅ 发现React脚本: {', '.join(react_scripts)}")
        else:
            print("❌ 未发现React脚本")
        
        # 检查CSS
        css_matches = re.findall(r'<link[^>]*href="([^"]*\.css[^"]*)"[^>]*>', content)
        if css_matches:
            print(f"✅ 发现CSS文件: {', '.join(css_matches)}")
        
        return True
        
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return False
    except Exception as e:
        print(f"❌ 检查页面时出错: {e}")
        return False

def check_js_files(base_url):
    """检查JavaScript文件"""
    print("\n🔍 检查JavaScript文件...")
    
    js_files = [
        "/src/main.tsx",
        "/src/App.tsx", 
        "/src/components/StartupScreen.tsx",
        "/src/hooks/useHmiState.ts"
    ]
    
    for js_file in js_files:
        url = urljoin(base_url, js_file)
        try:
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                print(f"✅ {js_file}: 可访问 ({len(response.text)} 字符)")
            else:
                print(f"❌ {js_file}: HTTP {response.status_code}")
        except Exception as e:
            print(f"❌ {js_file}: 无法访问 - {e}")

def main():
    """主函数"""
    print("🚀 开始检查HMI原型页面状态...")
    
    url = "http://localhost:5173"
    
    # 检查主页面
    success = check_page(url)
    
    if success:
        # 检查JavaScript文件
        check_js_files(url)
        print("\n✅ 页面检查完成")
    else:
        print("\n❌ 页面检查失败")

if __name__ == "__main__":
    main()
